package com.cherrish.demo.common.tree;

import lombok.Data;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

/**
 * @author ccl
 * @time 2018-10-22 10:49
 * @name TreeUtils
 * @desc:
 */
public class TreeUtils {
    public static <T extends BaseTreeGrid> List<T> formatTree(List<T> list, boolean flag){
        List<T> result = new ArrayList<T>();
        for(T node1 : list){
            boolean mark = false;
            for(T node2 : list){
                if(node1.getPid()!=null && node1.getPid().equals(node2.getId())){
                    node2.setLeaf(false);
                    mark = true;
                    if(node2.getChildren() == null) {
                        node2.setChildren(new ArrayList<BaseTreeGrid>());
                    }
                    node2.getChildren().add(node1);
                    if (flag) {
                        //默认已经全部展开
                    } else{
                        node2.setExpanded(false);
                    }
                    break;
                }
            }
            if(!mark){
                result.add(node1);
                if (flag) {
                    //默认已经全部展开
                } else{
                    node1.setExpanded(false);
                }
            }
        }
        return result;
    }
    @Data
    public static class BaseTreeGrid implements Serializable {

        private static final long serialVersionUID = -8832209413029497869L;

        /**
         * 节点id
         */
        private String id;

        /**
         * 父节点id
         */
        private String pid;

        /**
         * 节点样式
         */
        private String icon = "folder";

        /**
         * 是否为子叶节点
         */
        private Boolean leaf = true;

        /**
         * 是否展开
         */
        private Boolean expanded = true;

        /**
         * 子节点
         */
        private List<BaseTreeGrid> children;

        public BaseTreeGrid() {
        }

        public BaseTreeGrid(String id, String pid) {
            this.id = id;
            this.pid = pid;
        }
    }
}
